package com.tjetc.service.impl;

import com.tjetc.constant.CommonConstant;
import com.tjetc.dao.CommentDao;
import com.tjetc.dao.HotelDao;
import com.tjetc.dao.impl.CommentDaoImpl;
import com.tjetc.dao.impl.HotelDaoImpl;
import com.tjetc.exception.MessageException;
import com.tjetc.pojo.entity.Hotel;
import com.tjetc.pojo.entity.Review;
import com.tjetc.service.CommentService;

import java.util.List;

/**
 * @Author: itda
 * @Date: 2024/5/11 19:32
 * @Description: CommentServiceImpl
 */
public class CommentServiceImpl implements CommentService {

    private HotelDao hotelDao = new HotelDaoImpl();

    private CommentDao commentDao = new CommentDaoImpl();

    @Override
    public void list(Long hotelId) {
        try {
            Hotel hotel = hotelDao.getById(hotelId);
            if (hotel == null) {
                throw new MessageException(CommonConstant.NO_FIND_HOTEL);
            }
            List<Review> list = commentDao.getByHotelId(hotelId);
            if (list == null || list.size() == 0) {
                throw new MessageException(CommonConstant.HOTEL_NO_COMMENT);
            }
            list.stream().forEach(s -> System.out.println("顾客id:" + s.getGuestId() + ",评论内容:" + s.getComment()));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void getRating(Long hotelId) {
        try {
            Hotel hotel = hotelDao.getById(hotelId);
            if (hotel == null) {
                throw new MessageException(CommonConstant.NO_FIND_HOTEL);
            }
            List<Review> list = commentDao.getByHotelId(hotelId);
            if (list == null || list.size() == 0) {
                throw new MessageException(CommonConstant.HOTEL_NO_RATING);
            }
            double total = 0;
            double num = 0;
            for (Review review : list) {
                if (review.getRating() != 0) {
                    total += review.getRating();
                    num++;
                }
            }
            if (num == 0) {
                throw new MessageException(CommonConstant.HOTEL_NO_RATING);
            }
            double rating = total / num;
            hotelDao.updateRating(hotelId, rating);
            System.out.println("该酒店评级为:" + rating);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
